package com.fugood.lazylist;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.fugood.mybigday.db.DbAdapter;
import com.fugood.mybigday.db.SqlConstant.GuestInfo;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.widget.ImageView;

public class ImageLoader_SQL {
    
    MemoryCache memoryCache=new MemoryCache();
    DbAdapter mDbHelper;
    //FileCache fileCache;
    private Map<ImageView, Long> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, Long>());
    ExecutorService executorService; 
    Context context;
    
    public ImageLoader_SQL(Context context){
        //fileCache=new FileCache(context);
    	this.context = context;
    	mDbHelper = new DbAdapter(context);
    	mDbHelper.open();
        executorService=Executors.newFixedThreadPool(5);
    }
    
    final int stub_id= android.R.drawable.sym_def_app_icon;
    public void DisplayImage(long contactId, ImageView imageView)
    {
        imageViews.put(imageView, contactId);
        Bitmap bitmap=memoryCache.get(contactId);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(contactId, imageView);
            imageView.setImageResource(stub_id);
        }
    }
        
    private void queuePhoto(long contactId, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(contactId, imageView);
        executorService.submit(new PhotosLoader(p));
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    public InputStream openPhoto(long contactId) {
    	
	    Cursor cursor = mDbHelper.mDb.query(GuestInfo.TABLENAME
	    										, new String[]{GuestInfo.Photo}
	    										, GuestInfo.ID+"="+contactId
	    										, null,null,null,null);	    		
	     if (cursor == null) {
	         return null;
	     }
	     try {
	         if (cursor.moveToFirst()) {
	             byte[] data = cursor.getBlob(0);
	             if (data != null) {
	                 return new ByteArrayInputStream(data);
	             }
	         }
	     } finally {
	         cursor.close();
	     }
	     return null;
	 }
    
    
    
    
    private Bitmap getBitmap(long contactId) 
    {
        //File f=fileCache.getFile(url);

        Bitmap b = BitmapFactory.decodeStream(openPhoto(contactId));
        if(b!=null)
            return b;  
        else return null;
    }

    
    
    //Task for the queue
    private class PhotoToLoad
    {
        public long contactId;
        public ImageView imageView;
        public PhotoToLoad(long Id, ImageView i){
        	this.contactId = Id; 
            imageView=i;
        }
    }
    
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }
        
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.contactId);
            memoryCache.put(Long.toString(photoToLoad.contactId), bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }
    
    boolean imageViewReused(PhotoToLoad photoToLoad){
        long tag=imageViews.get(photoToLoad.imageView);
        if(tag !=photoToLoad.contactId)
            return true;
        return false;
    }
    
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        //fileCache.clear();
    }
    
    public void finish(){
    	mDbHelper.close();
    }

}
